package com.itcam.functionprogram_.chapter02.hiorder;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.*;
import java.util.stream.Collectors;

/**
 * @author : Cammy.Wu
 * Description : 简单流
 */

public class SimpleStream<T> {
    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);

        SimpleStream.of(list)
                .filter(i -> (i % 2) == 0)
                .map(i -> i * 2)
                .forEach(t -> System.out.print(Objects.toString(t, "") + " "));
    }


    private Collection<T> collection;

    private SimpleStream(Collection<T> collection) {
        this.collection = collection;
    }

    public static <T> SimpleStream<T> of(Collection<T> collection) {
        return new SimpleStream<>(collection);
    }

    // filter实现
    private SimpleStream<T> filter(Predicate<T> pre) {
        List<T> result = new ArrayList<>();
        for (T t : collection) {
            if (pre.test(t)) {
                result.add(t);
            }
        }
        return new SimpleStream<>(result);
    }

    // map实现
    private <U> SimpleStream<U> map(Function<T, U> fun) {
        List<U> result = new ArrayList<>();
        for (T t : collection) {
            U u = fun.apply(t);
            result.add(u);
        }
        return new SimpleStream<>(result);
    }

    // forEach实现
    private void forEach(Consumer<T> con) {
        for (T t : collection) {
            con.accept(t);
        }
    }
}
